import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Descriptions, Button, Tabs, Table, Space, Divider, message, Modal, Form, Input ,Switch} from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import { createStyles } from 'antd-style';
import { deptDetail, getDeptPositionList, deletePosition, getDeptPositionListUser, getPostList ,positionAdd,positionResourceAllocation, getPositionResources} from '@/services/system/departmentmanage';
import { DeleteOutlined, TeamOutlined, UserOutlined, PlusOutlined } from '@ant-design/icons';
import { Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { resourceList } from '@/services/system/resourcemanage';
interface PostType {
  id: string;
  postName: string;
  postCode: string;
  description: string;
  status: number;
  createTime: string;
}

interface PositionForm {
  postName: string;
  description: string;
  sort: number;
}

interface UserType {
  id: string;
  userName: string;
  name: string;
  phone: string;
  email: string;
  status: number;
}

interface ResourceType {
  id: string;
  remark: string;
  resourceName: string;
  children?: ResourceType[];
  status: number;
  delFlag: number;
  createTime: string;
  updateTime: string;
  createUser: string | null;
  updateUser: string | null;
  action: string | null;
  alias: string;
  iconPath: string | null;
  isOpen: number;
  path: string;
  resourceParentId: string | null;
  resourceType: string;
  sort: number;
  visible: number;
}

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03)',
  },
  subTitle: {
    backgroundColor: '#bae7ff',
    padding: '4px 16px',
    marginBottom: '16px',
  },
  buttonWrapper: {
    display: 'flex',
    justifyContent: 'center',
    marginTop: '24px',
  }
}));

const DepartmentView: React.FC = () => {
  const { styles } = useStyles();
  const location = useLocation();
  const navigate = useNavigate();
  const departmentData = location.state?.record || {};
  const [activeTab, setActiveTab] = useState('1');
  const [posts, setPosts] = useState<PostType[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [isUserModalVisible, setIsUserModalVisible] = useState(false);
  const [userList, setUserList] = useState<UserType[]>([]);
  const [userLoading, setUserLoading] = useState(false);
  const [currentPosition, setCurrentPosition] = useState<PostType | null>(null);
  const [selectedPositions, setSelectedPositions] = useState<PostType[]>([]);
  const [existingPositionIds, setExistingPositionIds] = useState<string[]>([]);
  const [isAssignModalVisible, setIsAssignModalVisible] = useState(false);
  const [resourceData, setResourceData] = useState<DataNode[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [currentAssignRecord, setCurrentAssignRecord] = useState<PostType | null>(null);

  useEffect(() => {
    if (departmentData) {
      fetchDepartmentDetail();
    }
  }, [departmentData]);

  const fetchDepartmentDetail = async () => {
    try {
      const response = await deptDetail({
        deptId: departmentData.id
      });
      console.log('Department Detail:', response);
      if (response.code === 200) {
        // 处理部门详情数据
      } else {
        console.error('Failed to fetch department detail:', response);
      }
    } catch (error) {
      console.error('Error fetching department detail:', error);
    }
  };

  const fetchDeptPosts = async () => {
    setLoading(true);
    try {
      const response = await getDeptPositionList({ deptId: departmentData.id });
      if (response.code === 200) {
        console.log('Department Posts:', response);
        setPosts(response.data || []);
        setExistingPositionIds(response.data.map((item: PostType) => item.id));
      }
    } catch (error) {
      console.error('Error fetching department posts:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (activeTab === '2') {
      fetchDeptPosts();
    }
  }, [activeTab]);

  const handleDelete = async (record: PostType) => {
    console.log('record:', record);

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除岗位 "${record.positionName}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deletePosition({ departmentId: departmentData.id, positionId: record.id });
          if (response.code === 200) {
            message.success('删除成功');
            fetchDeptPosts();
          }
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleAssign = async (record: PostType) => {
    setCurrentAssignRecord(record);
    setIsAssignModalVisible(true);
    setSelectedKeys([]); // 先清空选中状态

    try {
      // 并行获取资源树和已分配权限
      const [resourceResponse, assignedResponse] = await Promise.all([
        resourceList(),
        getPositionResources({
          departmentId: departmentData.id,
          positionId: record.id
        })
      ]);

      // 处理资源树数据
      if (resourceResponse.code === 200) {
        const transformData = (data: ResourceType[]): DataNode[] => {
          return data.map(item => ({
            key: item.id,
            title: item.remark || item.resourceName,
            children: item.children ? transformData(item.children) : undefined
          }));
        };
        setResourceData(transformData(resourceResponse.data));

        // 处理已分配权限数据
        if (assignedResponse.code === 200) {
          const getAllIds = (nodes: any[]): string[] => {
            let ids: string[] = [];
            nodes.forEach(node => {
              ids.push(node.id);
              if (node.children && node.children.length > 0) {
                ids = [...ids, ...getAllIds(node.children)];
              }
            });
            return ids;
          };

          const selectedIds = getAllIds(assignedResponse.data);
          console.log('选中的节点IDs:', selectedIds);

          // 确保只设置需要选中的节点
          setSelectedKeys(selectedIds);
        }
      } else {
        message.error(resourceResponse.msg || '获取资源列表失败');
      }
    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
    }
  };

  const handleViewUsers = async (record: PostType) => {
    console.log('record:', record);
    setCurrentPosition(record);
    setIsUserModalVisible(true);
    await fetchUserList(record.id);
  };

  const fetchUserList = async (positionId: string) => {
    setUserLoading(true);
    try {
      const response = await getDeptPositionListUser({
        departmentId: departmentData.id,
        positionId: positionId
      });
      if (response.code === 200) {
        setUserList(response.data || []);
      } else {
        message.error(response.msg || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      message.error('获取用户列表失败');
    } finally {
      setUserLoading(false);
    }
  };

  const handleUserModalClose = () => {
    setIsUserModalVisible(false);
    setUserList([]);
    setCurrentPosition(null);
  };

  const postColumns = [
    {
      title: '编号',
      dataIndex: 'id',
    },
    {
      title: '岗位名称',
      dataIndex: 'positionName',
    },
    {
      title: '描述',
      dataIndex: 'description',
    },
    {
      title: '排序',
      dataIndex: 'sort',
    },

    {
      title: '操作',
      key: 'action',
      render: (_, record: PostType) => (
        <Space split={<Divider type="vertical" />}>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            删除
          </Button>
          <Button
            type="link"
            size="small"
            icon={<TeamOutlined />}
            onClick={() => handleAssign(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            分配
          </Button>
          <Button
            type="link"
            size="small"
            icon={<UserOutlined />}
            onClick={() => handleViewUsers(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            人员
          </Button>
        </Space>
      ),
    },
  ];

  const handleBack = () => {
    navigate('/system/departmentmanage');
  };

  const showModal = () => {
    setIsModalVisible(true);
    fetchPostList();
  };

  const fetchPostList = async () => {
    setUserLoading(true);
    try {
      const response = await getPostList({
        deptId: departmentData.id
      });
      if (response.code === 200) {
        setUserList(response.data || []);
        const existingPositions = response.data.filter((item: PostType) =>
          existingPositionIds.includes(item.id)
        );
        setSelectedPositions(existingPositions);
      } else {
        message.error(response.msg || '获取岗位列表失败');
      }
    } catch (error) {
      console.error('获取岗位列表失败:', error);
      message.error('获取岗位列表失败');
    } finally {
      setUserLoading(false);
    }
  };
  const handleCancel = () => {
    form.resetFields();
    setIsModalVisible(false);
    setSelectedPositions([]);
  };

  const handleOk = async () => {
    try {
      if (selectedPositions.length === 0) {
        message.warning('请至少选择一个岗位');
        return;
      }
      console.log('Selected positio:', selectedPositions);
      // TODO: 调用添加岗位的接口ns
      const response = await positionAdd({
        departmentId: departmentData.id,
        positionIds: selectedPositions.map(item => item.id),
      });
      if (response.code === 200) {
        message.success('添加成功');
        setIsModalVisible(false);
        setSelectedPositions([]);
        fetchDeptPosts(); // 刷新列表
      } else {
        message.error(response.msg || '添加失败');
      }
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const userColumns = [
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status: number) => status === 0 ? '启用' : '禁用',
    },
  ];

  const userColumnsubmit = [
    {
      title: '编号',
      dataIndex: 'id',
    },
    {
      title: '岗位名称',
      dataIndex: 'positionName',
    },
    {
      title: '排序',
      dataIndex: 'sort',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status: number) => status === 0 ? '启用' : '禁用',
    },
    {
      title: '描述',
      dataIndex: 'description',
    },
  ];
  const items = [
    {
      key: '1',
      label: '基本信息',
      children: (
        <>
          <div className={styles.subTitle}>基本信息</div>
          <Descriptions column={2}>
            <Descriptions.Item label="部门名称">{departmentData.departmentName}</Descriptions.Item>
            <Descriptions.Item label="部门类型">
              {departmentData.departmentType === 0 ? '部门' : '其他'}
            </Descriptions.Item>
            <Descriptions.Item label="上级部门">{departmentData.fatherDepartmentName || '顶级'}</Descriptions.Item>
            <Descriptions.Item label="部门排序">{departmentData.sort}</Descriptions.Item>
          </Descriptions>
          <div style={{ marginTop: '24px' }}>
            <Descriptions column={1}>
              <Descriptions.Item label="部门描述">
                {departmentData.description || '暂无描述'}
              </Descriptions.Item>
            </Descriptions>
          </div>
        </>
      ),
    },
    {
      key: '2',
      label: '岗位管理',
      children: (
        <>
          <div style={{ marginBottom: 16 }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={showModal}
            >
              新增岗位
            </Button>
          </div>
          <Table
            columns={postColumns}
            dataSource={posts}
            loading={loading}
            rowKey="id"
          />
          <Modal
            title="新增岗位"
            open={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
            destroyOnClose
            width={1000}
            footer={[
              <Button key="cancel" onClick={handleCancel}>
                取消
              </Button>,
              <Button key="submit" type="primary" onClick={handleOk}>
                确定
              </Button>
            ]}
          >
            <Table
              columns={userColumnsubmit}
              dataSource={userList}
              loading={userLoading}
              rowKey="id"
              rowSelection={{
                type: 'checkbox',
                onChange: (selectedRowKeys, selectedRows) => {
                  console.log('selectedRows:', selectedRows);
                  setSelectedPositions(selectedRows);
                },
                selectedRowKeys: selectedPositions.map(item => item.id),
                getCheckboxProps: (record) => ({
                  disabled: existingPositionIds.includes(record.id),
                  defaultChecked: existingPositionIds.includes(record.id),
                }),
              }}
              pagination={{
                defaultPageSize: 10,
                showQuickJumper: true,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条`,
              }}
            />
          </Modal>
        </>
      ),
    },
  ];

  const handleAssignModalOk = async () => {
    try {
      if (!currentAssignRecord) {
        message.error('未选择岗位');
        return;
      }

      // 获取所有选中节点的父节点ID
      const getParentKeys = (treeData: any[], targetKeys: string[]): string[] => {
        const parentKeys = new Set<string>();

        const traverse = (node: any, parents: string[] = []) => {
          if (targetKeys.includes(node.key)) {
            parents.forEach(parentKey => parentKeys.add(parentKey));
          }

          if (node.children) {
            node.children.forEach((child: any) =>
              traverse(child, [...parents, node.key])
            );
          }
        };

        treeData.forEach(node => traverse(node));
        return Array.from(parentKeys);
      };

      // 合并选中的节点和它们的父节点
      const parentKeys = getParentKeys(resourceData, selectedKeys);
      const allKeys = [...new Set([...selectedKeys, ...parentKeys])];

      const response = await positionResourceAllocation({
        departmentId: departmentData.id,
        positionId: currentAssignRecord.id,
        resourcesIds: allKeys
      });

      if (response.code === 200) {
        message.success('分配权限成功');
        setIsAssignModalVisible(false);
        // 重要：清空选中状态
        setSelectedKeys([]);
        setCurrentAssignRecord(null);
      } else {
        message.error(response.msg || '分配权限失败');
      }
    } catch (error) {
      console.error('分配权限失败:', error);
      message.error('分配权限失败');
    }
  };
  const handleAssignModalCancel = () => {
    setIsAssignModalVisible(false);
    setSelectedKeys([]);
    setCurrentAssignRecord(null);
  };

  return (
    <PageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={items}
          />
          <div className={styles.buttonWrapper}>
            <Button type="primary" onClick={handleBack}>
              返回
            </Button>
          </div>
        </Card>
        <Modal
          title={`${currentPosition?.positionName || ''} - 人员列表`}
          open={isUserModalVisible}
          onCancel={handleUserModalClose}
          width={1000}
          footer={[
            <Button key="close" onClick={handleUserModalClose}>
              关闭
            </Button>
          ]}
        >
          <Table
            columns={userColumns}
            dataSource={userList}
            loading={userLoading}
            rowKey="id"
            pagination={{
              defaultPageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条`,
            }}
          />
        </Modal>
        <Modal
  title={`分配权限 - ${currentAssignRecord?.positionName}`}
  open={isAssignModalVisible}
  onOk={handleAssignModalOk}
  onCancel={handleAssignModalCancel}
  width={600}
>
  <Tree
    checkable
    checkedKeys={selectedKeys}
    onCheck={(checked) => {
      // 直接使用 checked 数组作为选中状态
      const checkedKeys = Array.isArray(checked) ? checked : checked.checked;
      setSelectedKeys(checkedKeys);
    }}
    treeData={resourceData}
    defaultExpandAll
    checkStrictly={true}  // 取消父子节点关联
  />
</Modal>
      </div>
    </PageContainer>
  );
};

export default DepartmentView;
